<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Publish\Controller;

use Common\Controller\AdminbaseController;
use Publish\Controller\AdminPostController;

class AdminHeadController extends AdminbaseController
{

    protected $posts_model;
    protected $image_model;
    protected $terms_model;
    protected $person_model;
    protected $term_relationships_model;


    function _initialize()
    {
        parent::_initialize();
        $this->posts_model = D("Publish/PubPosts");
        $this->image_model=D('Publish/PubImage');
        $this->terms_model = D("Publish/SystemTerms");
        $this->person_model = D('Publish/PubPerson');
        $this->term_relationships_model = D("Publish/SystemTermRelationships");
    }
    // 后台头像列表
    public function index()
    {
        $keyword = I('request.keyword');
        if(!empty($keyword)){
            $where['p.name'] = array('like',"%".$keyword."%");
        }
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['i.img_time']=array(
                array('EGT',strtotime($start_time))
            );
        }
        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['i.img_time'])){
                $where['i.img_time']=array();
            }
            array_push($where['i.img_time'], array('ELT',strtotime($end_time)));
        }
        $count=$this->image_model
            ->alias('i')
            ->join("__PUB_PERSON__ as p ON p.id=i.person_id")
            ->where($where)
            ->where(array('img_mark'=>0))
            ->where(array("img_url"=>array("neq"," ")))
            ->count();
        $page = $this->page($count, 10);
        $p_list=$this->image_model
            ->alias('i')
            ->join("__PUB_PERSON__ as p ON p.id=i.person_id")
            ->field("i.*,p.name")
            ->where($where)
            ->where(array('img_mark'=>0))
            ->where(array("img_url"=>array("neq"," ")))
            ->limit($page->firstRow , $page->listRows)
            ->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("head", $p_list);
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->display();
    }

    // 图片添加
    public function add()
    {
        $this->display();
    }

    // 图片添加提交
    public function add_post()

    {
        if (IS_POST) {
            empty($_POST['person_id']) && $this->error("请选择人物");
            $lists=I('post.');
//            $data['person_id'] = $_POST['person_id'];
            $data['img_name'] = $lists['thumb-name'];
            $data['img_url'] = $lists['img_url'];
            $data['img_mark'] = 0;
            $data['img_time'] = time();
//            $img_result=$this->image_model->where(array("person_id"=>$data['person_id'],"img_mark"=>0))->select();
//            if(count($img_result)<=0){
//                $img_result['person_id']=$data['person_id'];
//                $img_result['img_mark']=0;
//                $this->image_model->add($img_result);
//            }
            $url=$this->image_model
                ->where(array("person_id"=>$data['person_id']))
                ->field("img_url")
                ->find();
            if(empty($url['img_url']) || $url['img_url']==null){
                $resul = $this->image_model->where(array("person_id"=>$lists['person_id']))->save($data);

                if($resul){
                    $this->success("添加成功！");
                }else{
                    $this->error("添加失败");
                }
            }else{
                $this->error("该人物已有头像,不能添加");
            }
        }
    }

    // 图片编辑
    public function edit()
    {
        $id = I("get.id", 0, 'intval');
        $post=$this->image_model
            ->where(array('id'=>$id))
            ->find();
        $person=$this->person_model->where("id={$post['person_id']}")->find();
        $this->assign("person_name",$person['name']);
        $this->assign("post", $post);
        $this->assign("person_id",$post['person_id']);
        $this->display();
    }


    // 图片编辑提交
    public function edit_post()
    {
        if (IS_POST) {
            $lists=I('post.');
            empty($_POST['person_id']) && $this->error("请选择人物");
            $post=$this->image_model
                ->where(array('id'=>$lists['img_id']))
                ->find();
            $data['person_id'] = $_POST['person_id'];
            if($post['img_url']!=$lists['img_url']&&$post['img_name']!=$lists['thumb-name']){
                unlink(C('UPLOADPATH') . $post['img_url']);
//                $this->image_model->where(array('img_url'=>$post['img_url']))->delete();
            }
            $data['img_name'] = $lists['thumb-name'];
            $data['img_url'] = $lists['img_url'];
            $data['img_mark'] = 0;
            $data['img_time'] = time();
            $resul = $this->image_model->where(array('id'=>$lists['img_id']))->save($data);
            if($resul==true){
                $this->success("图片添加成功！");
            }else{
                $this->error("图片添加失败!");
            }

        }
    }

    // 文章排序
    public function listorders()
    {
        $status = parent::_listorders($this->term_relationships_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    /**
     * 文章列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where = array())
    {
        $term_id = I('request.term', 0, 'intval');

        $where['post_type'] = array(array('eq', 1), array('exp', 'IS NULL'), 'OR');

        if (!empty($term_id)) {
            $where['b.term_id'] = $term_id;
            $term = $this->terms_model->where(array('term_id' => $term_id))->find();
            $this->assign("term", $term);
        }

        $start_time = I('request.start_time');
        if (!empty($start_time)) {
            $where['post_date'] = array(
                array('EGT', $start_time)
            );
        }

        $end_time = I('request.end_time');
        if (!empty($end_time)) {
            if (empty($where['post_date'])) {
                $where['post_date'] = array();
            }
            array_push($where['post_date'], array('ELT', $end_time));
        }

        $keyword = I('request.keyword');
        if (!empty($keyword)) {
            $where['name'] = array('like', "%$keyword%");
        }

        $this->posts_model
            ->alias("a")
            ->where($where);

        if (!empty($term_id)) {
            $this->posts_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }

        $count = $this->posts_model->count();

        $page = $this->page($count, 20);

        $this->posts_model
            ->alias("a")
            ->join("__SYSTEM_USERS__ c ON a.post_author = c.id")
            ->where($where)
            ->limit($page->firstRow, $page->listRows)
            ->order("a.post_date DESC");
        if (empty($term_id)) {
            $this->posts_model->field('a.*,c.user_login,c.user_nicename');
        } else {
            $this->posts_model->field('a.*,c.user_login,c.user_nicename,b.listorder,b.tid');
            $this->posts_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
        $posts = $this->posts_model->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget", array_merge($_GET, $_POST));
        $this->assign("posts", $posts);
    }

    // 获取文章分类树结构 select 形式
    private function _getTree()
    {
        $term_id = empty($_REQUEST['term']) ? 0 : intval($_REQUEST['term']);
        $result = $this->terms_model->order(array("listorder" => "asc"))->select();

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id'] = $r['term_id'];
            $r['parentid'] = $r['parent'];
            $r['selected'] = $term_id == $r['term_id'] ? "selected" : "";
            $array[] = $r;
        }

        $tree->init($array);
        $str = "<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }

    // 获取文章分类树结构
    private function _getTermTree($term = array())
    {
        $result = $this->terms_model->order(array("listorder" => "asc"))->select();

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id'] = $r['term_id'];
            $r['parentid'] = $r['parent'];
            $r['selected'] = in_array($r['term_id'], $term) ? "selected" : "";
            $r['checked'] = in_array($r['term_id'], $term) ? "checked" : "";
            $array[] = $r;
        }

        $tree->init($array);
        $str = "<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }

    // 人物头像删除
    public function delete()
    {
        if (isset($_GET['id'])) {
            $id = I("get.id", 0, 'intval');
            $list=$this->image_model->where(array('id' => $id))->find();
            $list['img_name']="";
            $list['img_url']="";
            $list['img_time']="";
            $d_result=$this->image_model->where(array('id' => $id))->save($list);
            if($d_result){
                unlink(C('UPLOADPATH').$list['img_url']);
                $this->success("删除成功！");
            }else{
                $this->error("删除失败！");
            }
        }

        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            /*删除多个数据时，循环删除对应文件*/
            for($i=0;$i<count($ids);$i++){
                //删除时，删除对应图片文件
                $imgss = $this->image_model->where(array('id'=>$ids[$i]))->find();
                $img_url = $imgss['img_url'];
                $imgss['img_name']="";
                $imgss['img_url']="";
                $imgss['img_time']='';
                $d_result=$this->image_model->where(array('id' => $ids[$i]))->save($imgss);
                if(!$d_result){
                    $this->error("id为".$id."的图片删除失败");
                }else{
                    unlink(C('UPLOADPATH').$img_url);
                }
            }
            $this->success("删除成功");
        }
    }

    // 文章审核
    public function check()
    {
        if (isset($_POST['ids']) && $_GET["check"]) {
            $ids = I('post.ids/a');

            if ($this->posts_model->where(array('id' => array('in', $ids)))->save(array('post_status' => 1)) !== false) {
                $this->success("审核成功！");
            } else {
                $this->error("审核失败！");
            }
        }
        if (isset($_POST['ids']) && $_GET["uncheck"]) {
            $ids = I('post.ids/a');

            if ($this->posts_model->where(array('id' => array('in', $ids)))->save(array('post_status' => 0)) !== false) {
                $this->success("取消审核成功！");
            } else {
                $this->error("取消审核失败！");
            }
        }
    }

    // 文章置顶
    public function top()
    {
        if (isset($_POST['ids']) && $_GET["top"]) {
            $ids = I('post.ids/a');

            if ($this->posts_model->where(array('id' => array('in', $ids)))->save(array('istop' => 1)) !== false) {
                $this->success("置顶成功！");
            } else {
                $this->error("置顶失败！");
            }
        }
        if (isset($_POST['ids']) && $_GET["untop"]) {
            $ids = I('post.ids/a');

            if ($this->posts_model->where(array('id' => array('in', $ids)))->save(array('istop' => 0)) !== false) {
                $this->success("取消置顶成功！");
            } else {
                $this->error("取消置顶失败！");
            }
        }
    }

    // 文章推荐
    public function recommend()
    {
        if (isset($_POST['ids']) && $_GET["recommend"]) {
            $ids = I('post.ids/a');

            if ($this->posts_model->where(array('id' => array('in', $ids)))->save(array('recommended' => 1)) !== false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if (isset($_POST['ids']) && $_GET["unrecommend"]) {
            $ids = I('post.ids/a');

            if ($this->posts_model->where(array('id' => array('in', $ids)))->save(array('recommended' => 0)) !== false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }

    // 文章批量移动
    public function move()
    {
        if (IS_POST) {
            if (isset($_GET['ids']) && $_GET['old_term_id'] && isset($_POST['term_id'])) {
                $old_term_id = I('get.old_term_id', 0, 'intval');
                $term_id = I('post.term_id', 0, 'intval');
                if ($old_term_id != $term_id) {
                    $ids = explode(',', I('get.ids/s'));
                    $ids = array_map('intval', $ids);

                    foreach ($ids as $id) {
                        $this->term_relationships_model->where(array('object_id' => $id, 'term_id' => $old_term_id))->delete();
                        $find_relation_count = $this->term_relationships_model->where(array('object_id' => $id, 'term_id' => $term_id))->count();
                        if ($find_relation_count == 0) {
                            $this->term_relationships_model->add(array('object_id' => $id, 'term_id' => $term_id));
                        }
                    }

                }

                $this->success("移动成功！");
            }
        } else {
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->terms_model->order(array("path" => "ASC"))->select();
            $new_terms = array();
            foreach ($terms as $r) {
                $r['id'] = $r['term_id'];
                $r['parentid'] = $r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl = "<option value='\$id'>\$spacer\$name</option>";
            $tree = $tree->get_tree(0, $tree_tpl);

            $this->assign("terms_tree", $tree);
            $this->display();
        }
    }

    // 文章批量复制
    public function copy()
    {
        if (IS_POST) {
            if (isset($_GET['ids']) && isset($_POST['term_id'])) {
                $ids = explode(',', I('get.ids/s'));
                $ids = array_map('intval', $ids);
                $uid = sp_get_current_admin_id();
                $term_id = I('post.term_id', 0, 'intval');
                $term_count = $terms_model = M('SystemTerms')->where(array('term_id' => $term_id))->count();
                if ($term_count == 0) {
                    $this->error('分类不存在！');
                }

                $data = array();

                foreach ($ids as $id) {
                    $find_post = $this->posts_model->field('post_keywords,post_source,post_content,post_title,post_excerpt,smeta')->where(array('id' => $id))->find();
                    if ($find_post) {
                        $find_post['post_author'] = $uid;
                        $find_post['post_date'] = date('Y-m-d H:i:s');
                        $find_post['post_modified'] = date('Y-m-d H:i:s');
                        $post_id = $this->posts_model->add($find_post);
                        if ($post_id > 0) {
                            array_push($data, array('object_id' => $post_id, 'term_id' => $term_id));
                        }
                    }
                }

                if ($this->term_relationships_model->addAll($data) !== false) {
                    $this->success("复制成功！");
                } else {
                    $this->error("复制失败！");
                }
            }
        } else {
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->terms_model->order(array("path" => "ASC"))->select();
            $new_terms = array();
            foreach ($terms as $r) {
                $r['id'] = $r['term_id'];
                $r['parentid'] = $r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl = "<option value='\$id'>\$spacer\$name</option>";
            $tree = $tree->get_tree(0, $tree_tpl);

            $this->assign("terms_tree", $tree);
            $this->display();
        }
    }

    // 文章回收站列表
    public function recyclebin()
    {
        $this->_lists(array('post_status' => array('eq', 3)));
        $this->_getTree();
        $this->display();
    }

    // 清除已经删除的文章
    public function clean()
    {
        if (isset($_POST['ids'])) {
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status = $this->posts_model->where(array("id" => array('in', $ids), 'post_status' => 3))->delete();
            $this->term_relationships_model->where(array('object_id' => array('in', $ids)))->delete();

            if ($status !== false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        } else {
            if (isset($_GET['id'])) {
                $id = I("get.id", 0, 'intval');
                $status = $this->posts_model->where(array("id" => $id, 'post_status' => 3))->delete();
                $this->term_relationships_model->where(array('object_id' => $id))->delete();

                if ($status !== false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }

    // 文章还原
    public function restore()
    {
        if (isset($_GET['id'])) {
            $id = I("get.id", 0, 'intval');
            if ($this->posts_model->where(array("id" => $id, 'post_status' => 3))->save(array("post_status" => "1"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }

}